/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * email:nur01@qq.com
 * @flow
 */

import React, {Component} from 'react';
import {
    DeviceEventEmitter,
    Image,
    ListView,
    RefreshControl,
    StyleSheet,
    Text,
    TouchableOpacity,
    View
} from 'react-native';
import StyleUtils from "../../../res/styles/StyleUtils";
import Navigation from "../../../custom/Navigation";
import ViewUtils from "../../../utils/ViewUtils";
import {KeyboardAwareScrollView} from 'react-native-keyboard-aware-scroll-view'
import LoginPage from "../LoginPage";
import RegisterIBMThreePage from "./RegisterIBMThreePage";
import IparNetwork, {SERVER_TYPE} from "../../../httpUtils/IparNetwork";
import I18n from "../../../res/language/i18n";
import ModalListUtils from "../../../utils/ModalListUtils";
import CommonUtils from "../../../common/CommonUtils";
import IparInput from "../../../custom/IparInput";


let clickTypes = {country: 'country', province: 'province', city: 'city', position: 'position'};

let _countryData = [];
let _provinceData = [];
let _cityData = [];
let _positionData = [];

export default class RegisterIBMTowPage extends Component {


    constructor(props) {
        super(props);

        let ds = new ListView.DataSource({
            rowHasChanged: (r1, r2) => r1 !== r2,
        });


        this.userMailbox_number = '';
        this.userUnit = '';

        this.iparNetwork = new IparNetwork();
        this.state = {
            //isDateTimePickerVisible: false,

            //userInfo
            userCountry: I18n.t('default.selectCountry'),
            userProvince: I18n.t('default.selectProvince'),
            userCity: I18n.t('default.selectCity'),
            userPosition: I18n.t('default.selectDistrict'),

            addressId: '',

            modalVisible: false,
            loading: true,

            countryData: ds,
            provinceData: ds,
            cityData: ds,
            positionData: ds,

            countryIso: '',

            modalType: '',


            userPostCode: '',


            notNullProvince: false,
            notNullCity: false,
            notNullPosition: false,


        }
    }


    componentDidMount() {


        this.onLoadData()
    }

    /**
     * 获取数据
     * @param level  是哪一个（例如：新疆=1，乌鲁木齐=2，。。。++）
     * @param parent 是哪一个的 （例如：新疆=》乌鲁木齐，喀什。。。。）
     */
    onLoadData(level, parent) {

        this.setState({
            loading: true,
        })

        let param = '';
        if (level && parent) {
            param = 'level=' + level + '&parent=' + parent;
        }
        this.iparNetwork.getRequest(SERVER_TYPE.logistics + 'region?', param)
            .then((result) => {
                this.setState({
                    loading: false,
                });


                if (result) {
                    switch (level) {
                        case 1://province
                            _provinceData = result;
                            this.setState({
                                notNullCity: false,
                                userCity: I18n.t('default.selectCity'),
                                notNullProvince: result.length > 0,
                                provinceData: this.state.provinceData.cloneWithRows(result),
                            });
                            break;
                        case 2://city
                            _cityData = result;
                            this.setState({
                                notNullPosition: false,
                                userPosition: I18n.t('default.selectDistrict'),
                                notNullCity: result.length > 0,
                                cityData: this.state.cityData.cloneWithRows(result),
                            });
                            break;
                        case 3://Position
                            _positionData = result;
                            this.setState({
                                notNullPosition: result.length > 0,
                                positionData: this.state.positionData.cloneWithRows(result),
                            });
                            break;
                        default: {//国家的数据
                            if (level !== 4) {
                                _countryData = result;
                                this.setState({
                                    countryData: this.state.countryData.cloneWithRows(result),
                                })
                            }
                        }
                    }


                } else {
                    console.log('RegisterIBMOnePage--submit-fail: ', result);
                    DeviceEventEmitter.emit(I18n.t('default.fail'));
                }
            })
            .catch((error) => {
                this.setState({
                    loading: false,
                });
                console.log('RegisterIBMOnePage--submit-error: ', error);
                DeviceEventEmitter.emit(I18n.t('default.fail'))
            })
    }

    /**
     * 点击NEX
     */
    submit(type) {


        if (this.state.userCountry === I18n.t('default.selectCountry')) {
            DeviceEventEmitter.emit('toast', I18n.t('default.selectCountry'));
            return;
        }
        if (this.state.notNullProvince && this.state.userProvince === I18n.t('default.selectProvince')) {
            DeviceEventEmitter.emit('toast', I18n.t('default.selectProvince'));
            return;
        }

        if (this.state.notNullCity && this.state.userCity === I18n.t('default.selectCity')) {
            DeviceEventEmitter.emit('toast', I18n.t('default.selectCity'));

            return;
        }
        if (this.state.notNullPosition && this.state.userPosition === I18n.t('default.selectDistrict')) {
            DeviceEventEmitter.emit('toast', I18n.t('default.selectDistrict'));

            return;
        }

        if (!this.userMailbox_number) {
            DeviceEventEmitter.emit('toast', I18n.t('default.streetNumber'));
            return;
        }

        if (!this.userUnit) {
            DeviceEventEmitter.emit('toast', I18n.t('default.buildingName'));
            return;
        }
        if (!this.state.userPostCode) {
            DeviceEventEmitter.emit('toast', I18n.t('default.postalCode'));
            return;
        }

        CommonUtils.showLoading();



        let _province = '';
        if (this.state.notNullProvince) {
            _province = this.state.userProvince + ',';
        }

        let _city = '';
        if (this.state.notNullCity) {
            _city = this.state.userCity + ','
        }
        let _position = '';
        if (this.state.notNullPosition) {
            _position = this.state.userPosition + ','
        }


        let address = this.state.userCountry + ',' + _province + _city + _position;


        let formData = new FormData();
        formData.append('user_id', this.props.userId);
        formData.append('address_id', this.state.addressId);
        formData.append('street_name', this.userMailbox_number);
        formData.append('building', this.userUnit);
        formData.append('address', address);
        formData.append('postcode', this.state.userPostCode);
        this.iparNetwork.getPostFrom(SERVER_TYPE.admin + 'updateUserInfo', formData)
            .then((result) => {
                CommonUtils.dismissLoading();

                if (result.code === 200) {
                    DeviceEventEmitter.emit(I18n.t('default.success'));
                    if (type === 1) {
                        new CommonUtils().popToRoute(this, 'LoginPage')
                    } else {
                        this.startNex();
                    }
                } else {
                    console.log('RegisterIBMTowPage--submit-fail: ', result);
                    DeviceEventEmitter.emit(I18n.t('default.fail'))
                }
            })
            .catch((error) => {
                CommonUtils.dismissLoading();

                console.log('RegisterIBMTowPage--submit-error: ', error);
                DeviceEventEmitter.emit(I18n.t('default.fail'))
            })

    }


    /**
     * 条第二个注册页面
     */
    startNex() {
        this.props.navigator.push({
            component: RegisterIBMThreePage,
            name: 'RegisterIBMThreePage',
            params: {
                userId: this.props.userId,
                country: this.state.countryIso,
            }
        });
    }


    /**
     * 点击
     * @param type
     */
    onClick(type) {
        switch (type) {
            case clickTypes.country:
                this.setState({
                    modalVisible: true,
                    modalType: clickTypes.country,
                });
                break;
            case clickTypes.province:
                if (this.state.notNullProvince) {
                    this.setState({
                        modalVisible: true,
                        modalType: clickTypes.province,
                    });
                } else {
                    DeviceEventEmitter.emit('toast', '请选择国家')
                }
                break;
            case clickTypes.city:
                if (this.state.notNullCity) {
                    this.setState({
                        modalVisible: true,
                        modalType: clickTypes.city,
                    });
                } else {
                    DeviceEventEmitter.emit('toast', '请选择省份')
                }
                break;
            case clickTypes.position:
                if (this.state.notNullPosition) {
                    this.setState({
                        modalVisible: true,
                        modalType: clickTypes.position,
                    });
                } else {
                    DeviceEventEmitter.emit('toast', '请选择城市')
                }
                break;
        }

    }


    /**
     * modal 的 item click
     * @param index
     * @param value
     */
    onModalItemClick(index, value) {

        let level = '';
        switch (this.state.modalType) {
            case clickTypes.country://选择国家
                level = 1;

                this.setState({
                    userCountry: value,
                    countryIso: _countryData[index].iso,
                    modalVisible: false,
                    addressId: _countryData[index].id,


                    notNullProvince: false,
                    notNullCity: false,
                    notNullPosition: false,

                    userProvince: I18n.t('default.selectProvince'),
                    userCity: I18n.t('default.selectCity'),
                    userPosition: I18n.t('default.selectDistrict'),

                    userPostCode: _countryData[index].postcode,

                });

                break;
            case clickTypes.province://选择省份
                level = 2;
                this.setState({
                    userProvince: value,
                    modalVisible: false,
                    addressId: _provinceData[index].id,
                    userCity: I18n.t('default.selectCity'),
                    userPostCode: _provinceData[index].postcode,

                });
                break;
            case clickTypes.city://选择城市
                level = 3;
                this.setState({
                    userCity: value,
                    userPosition: I18n.t('default.selectDistrict'),
                    modalVisible: false,
                    addressId: _cityData[index].id,
                    userPostCode: _cityData[index].postcode,

                });
                break;
            case clickTypes.position://选择区
                level = 4;
                this.setState({
                    userPosition: value,
                    modalVisible: false,
                    addressId: _positionData[index].id,
                    userPostCode: _positionData[index].postcode,

                });
                break;
        }


        this.onLoadData(level, value)
    }

    /**
     * init
     * */
    render() {

        let modalData = this.state.countryData;
        switch (this.state.modalType) {
            case clickTypes.province:
                modalData = this.state.provinceData;
                break;
            case clickTypes.city:
                modalData = this.state.cityData;
                break;
            case clickTypes.position:
                modalData = this.state.positionData;
                break;
        }

        return (
            <View style={StyleUtils.flex}>
                <Navigation
                    titleImage={require('../../../res/images/ic_ipar_logo.png')}
                    onClickLeftBtn={() => {
                        new CommonUtils().popToRoute(this, 'LoginPage')
                    }}
                />

                <KeyboardAwareScrollView
                    refreshControl={
                        <RefreshControl
                            refreshing={this.state.loading}
                            onRefresh={() => {
                            }}
                        />
                    }>
                    <View style={{padding: 16}}>
                        {/*title*/}
                        {ViewUtils.getTitleView(I18n.t('default.register'), I18n.t('default.contactAddress'))}


                        {ViewUtils.getButtunMenu(this.state.userCountry,
                            () => this.onClick(clickTypes.country), StyleUtils.marginTop)}

                        {this.state.notNullProvince ?
                            ViewUtils.getButtunMenu(this.state.userProvince,
                                () => this.onClick(clickTypes.province), StyleUtils.marginTop)
                            : null
                        }

                        {this.state.notNullCity ?
                            ViewUtils.getButtunMenu(this.state.userCity,
                                () => this.onClick(clickTypes.city), StyleUtils.marginTop)
                            : null
                        }

                        {this.state.notNullPosition ?
                            ViewUtils.getButtunMenu(this.state.userPosition,
                                () => this.onClick(clickTypes.position), StyleUtils.marginTop)
                            : null
                        }

                        <IparInput
                            onChangeText={(text) => this.userMailbox_number = text}
                            placeholder={I18n.t('default.streetNumber')}/>

                        <IparInput
                            onChangeText={(text) => this.userUnit = text}
                            placeholder={I18n.t('default.buildingName')}/>


                        <IparInput
                            onChangeText={(text) => this.state.userPostCode = text}
                            placeholder={this.state.userPostCode ? this.state.userPostCode : I18n.t('default.postalCode')}/>

                        {ViewUtils.getButton(I18n.t('default.next'), () => this.submit(0), [StyleUtils.marginTop])}
                        {ViewUtils.getButton(I18n.t('default.zanCun'), () => this.submit(1), [StyleUtils.marginTop, styles.zanBtn], {color: 'black'})}
                    </View>
                </KeyboardAwareScrollView>


                <ModalListUtils
                    visible={this.state.modalVisible}
                    close={() => this.setState({
                        modalVisible: false,
                    })}
                    dataParam={'name'}
                    onPress={(index, text) => this.onModalItemClick(index, text)}
                    dataSource={modalData}
                />


            </View>
        );
    }
}


const styles = StyleSheet.create({
    zanBtn: {
        backgroundColor: 'white',
        borderWidth: 1,
        borderColor: 'black',
        marginBottom: 40
    }
});


